package com.goddess.yeecolor.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.goddess.yeecolor.Modle.ActivityFragmentModle;
import com.goddess.yeecolor.Modle.MyHuoDongInfo;
import com.goddess.yeecolor.Modle.controlInfo;
import com.goddess.yeecolor.R;
import com.goddess.yeecolor.activity.ExerciseItem2Activit;
import com.goddess.yeecolor.activity.ExerciseItemActivity;
import com.goddess.yeecolor.activity.Exerciseltem3Activity;
import com.goddess.yeecolor.adapter.MyHuoDongAdapter;
import com.goddess.yeecolor.base.BaseFragment;
import com.goddess.yeecolor.interfaceAll.OnClickListener;
import com.goddess.yeecolor.tools.JumpIntents;
import com.goddess.yeecolor.tools.LogUtils;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.RecycleViewDivider;
import com.goddess.yeecolor.view.dialog_progress;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的活动fragment
 */
public class MyHuoDongAllFragment extends BaseFragment{
    private List<ActivityFragmentModle >mList=new ArrayList<>();;
    private MyHuoDongAdapter adapter;
    private XRefreshView xRefreshView;
    private RecyclerView mRecyclerview;
    private TextView text;
    private LinearLayoutManager manager;
    private int pid;//哪个frgament
    private String tag;
    private FrameLayout fragmelayout;
    private View mView;

    private Bundle mBundle;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView==null){
            mView=inflater.inflate(R.layout.fragment_huodong,container,false);
            initFindView();
        }
        return mView;
    }
    private dialog_progress dialog_progress;
    private void setProgress(){
        dialog_progress=new dialog_progress(getActivity());
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBundle=getArguments();
        if (mBundle!=null){
            pid=mBundle.getInt("id");
        }
    }
    public static MyHuoDongAllFragment newInstance(int id) {

        MyHuoDongAllFragment newFragment = new MyHuoDongAllFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("id",id);
        newFragment.setArguments(bundle);
        return newFragment;
    }
    /**
     * 判断显示那个fragment
     */
    private void isFragment(int state){

    }
    @Override
    public void initFindView() {

        xRefreshView= (XRefreshView) mView.findViewById(R.id.huoodng_xrefreshview);
        mRecyclerview= (RecyclerView) mView.findViewById(R.id.huoodng_recyclerview);
        manager = new LinearLayoutManager(getActivity());
        mRecyclerview.setLayoutManager(manager);
        mRecyclerview.addItemDecoration(new RecycleViewDivider(getActivity(), manager.HORIZONTAL, 1, Color.rgb(211, 211, 211)));
        initData();//数据

    }
    private Bundle bundle;
    private void setEmpty(){
        if (mList.size()>0){
            fragmelayout.setBackground(null);
        }
        else {
            fragmelayout.setBackground(getResources().getDrawable(R.mipmap.nulldata));
        }
    }
    private void setAdapter(){
        adapter=new MyHuoDongAdapter(mList,getActivity(),getActivity());
        mRecyclerview.setAdapter(adapter);
//        xRefreshMethed.setRefrsh(xRefreshView);
        /**
         * 写到这
         */
        View view=LayoutInflater.from(getActivity()).inflate(R.layout.empty,null);
        xRefreshView.setEmptyView(view);

        xRefreshView.setSilenceLoadMore();
        xRefreshView.setPreLoadCount(4);
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setAutoLoadMore(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.enablePullUpWhenLoadCompleted(true);
        adapter.notifyDataSetChanged();
//        adapter.setCustomLoadMoreView(new XRefreshViewFooter(getActivity()));
        initOnClck();

        /**
         *
         * item点击事件
         */
        adapter.setOnItemClickListener(new OnClickListener() {
            @Override
            public void OnClick(View view, int position) {
                ActivityFragmentModle modle=mList.get(position);
                bundle=new Bundle();
                bundle.putString("typed",modle.getCollection_id()+"");
                bundle.putString("title","");

                bundle.putString("id",modle.getEventsid()+"");
                int state=modle.getStatae();
                if (state==2){
                    JumpIntents.startIntent(getActivity(), ExerciseItem2Activit.class,bundle);
                }
                else if (state==1){
                    JumpIntents.startIntent(getActivity(), Exerciseltem3Activity.class,bundle);
                }
                else if (state==0){
                    JumpIntents.startIntent(getActivity(), ExerciseItemActivity.class,bundle);
                }

            }

            @Override
            public void OnLongClick(View view, int position) {

            }
        });

    }

    private void setRequest(int state){
        setProgress();
        Map<Object,Object> map=new HashMap<>();
        map.put("unique", SharePreceUtils.getOther("user","unique"));
        map.put("state",state+"");
        map.put("page",page+"");
        LogUtils.getInstence().info(MyUrl.ORDERSList+"?unique="+SharePreceUtils.getOther("user","unique")+"&state="+state+"&page=1");
        OkttpUtils.getIntence().OkttpPost(MyUrl.ORDERSList,map,handler,1);
    }
    @Override
    public void initData() {

        MyHuoDongInfo person = null;
        if (pid==1) {//显示全部  fragment
            setRequest(0);
        }
        else if (pid==2){//待付款
            setRequest(1);

        }
        else if (pid==3){////待参与
            setRequest(2);

        }
        else if (pid==4){//已完成
            setRequest(3);

        }

    }
    @Override
    public void initOnClck() {
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener(){
            @Override
            public void onRefresh() {
                super.onRefresh();
                //下拉刷新
                initOnRefresh();
            }


            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                //上拉加载
                initLoadMore();
            }
        });



    }

    /**
     * 下拉刷新
     */
    int page=1;
    private void initOnRefresh() {
        Tag="PULL";
        page=1;
        if (adapter!=null){
            mList.clear();
            adapter.clear();
            adapter.notifyDataSetChanged();//防止数据不再顶部  刷新
        }
        initData();
    }


    /**
     * 上拉加载
     */
    private void initLoadMore() {
        page++;
        Tag="LOAD";
        initData();
        //模拟没有更多数据的情况
//        xRefreshView.setLoadComplete(true);
    }



    private String Tag="NULL";
    private String jsonString;
    private int code;

    private String price,title,extens;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {

                jsonString=msg.getData().getString("result");
                JSONObject object=new JSONObject(jsonString);
                code=object.getInt("code");
                if (code==100){
                    JSONObject extend=object.getJSONObject("extends");
                    extens=extend.optString("endfull");
                    if (object.has("result")){
                        JSONArray result=object.getJSONArray("result");

                        for (int i=0;i<result.length();i++){
                            JSONObject itemdata=result.getJSONObject(i);
                            ActivityFragmentModle info=new ActivityFragmentModle();
                            info.setId(itemdata.getInt("id"));
                            info.setUnique(itemdata.optString("unique"));
                            info.setTyped(itemdata.optString("typed"));
                            info.setBuy_id(itemdata.optString("buy_id"));
                            info.setAddtime(itemdata.optString("addtime"));
                            info.setOrder_id(itemdata.optString("order_id"));
                            JSONObject events=itemdata.getJSONObject("events");

                            info.setEventsid(events.optString("id"));
                            info.setTitle(events.optString("title"));
                            LogUtils.getInstence().info(events.optString("title"));
                            info.setThumb(events.optString("thumb"));
                            info.setAdd_date(itemdata.optString("add_date"));

                            JSONArray control=itemdata.getJSONArray("control");//获取按钮类型
                            List<controlInfo>controlInfoList=new ArrayList<>();
                            for (int j=0;j<control.length();j++){
                                controlInfo contro=new controlInfo();
                                JSONObject cs=control.getJSONObject(j);
                                contro.setName(cs.optString("name"));
                                controlInfoList.add(contro);
                            }
                            info.setControlInfoList(controlInfoList);
                            if (Tag.equals("LOAD")){
                                mList.add(info);
                                adapter.insert(info,adapter.getAdapterItemCount());
                            }
                            else if (Tag.equals("NULL")){
                                mList.add(info);
                            }
                            else if (Tag.equals("PULL")){
//                            mList.add(info);
                                adapter.insert(info,adapter.getAdapterItemCount());
                            }
                        }
                    }
                    else {
                        if (extens.equals("0")){

                            xRefreshView.stopLoadMore(true);

                        }
                    }

                }
                else {
                    JSONObject extend=object.getJSONObject("extends");
                    if (extend.optString("endfull").equals("0")){
                        ToastUtils.toast("暂无数据");
                        xRefreshView.stopLoadMore(true);

                    }
                }
                if (Tag.equals("LOAD")){

                    if (extens.equals("0")){
                        xRefreshView.stopLoadMore(true);
//                        xRefreshView.setHideFooterWhenComplete(true);
                    }
                    else {
                        xRefreshView.stopLoadMore(true);
                    }
                }
                else if (Tag.equals("PULL")){
                    xRefreshView.stopRefresh(true);

                }
                else {//第一次进来获取数据
                    setAdapter();
                }

                if (dialog_progress!=null&&dialog_progress.isShowing()){
                    dialog_progress.dismiss();
                }

            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog_progress!=null&& dialog_progress.isShowing()){
            dialog_progress.dismiss();
        }
    }
}
